package com.constants;

import java.lang.reflect.Method;
import java.nio.MappedByteBuffer;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 常量工具 Created by Mark Hsiu
 */
public class ConstantUtil {

	/**
	 * I/O线程数经验值是[CPU核数 + 1，CPU核数*2 ]之间 当前系统的进程*2
	 */
	private static int workerThreads = Runtime.getRuntime()
			.availableProcessors();
	private static final ExecutorService pools = Executors
			.newFixedThreadPool(2 * workerThreads);

	public static final int TIMEOUT = 10000;// 10s
	public static final String S_SEP = "|";
	public static final String S_CHILD = ":";

	/**
	 * TCP层面的发送缓冲区大小设置
	 */
	public static final int socketSndBufSize = 1024 * 64;// 64k
	/**
	 * TCP层面的接收缓冲区大小设置
	 */
	public static final int socketRcvBufSize = 1024 * 64;// 64k

	public static int getWorkerThreads() {
		return workerThreads;
	}

	public static void setWorkerThreads(int workers) {
		workerThreads = workers;
	}

	public static void threadPools(Runnable command) {
		pools.execute(command);
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static void cleanMappedByte(final MappedByteBuffer buffer) {
		AccessController.doPrivileged(new PrivilegedAction() {
			@SuppressWarnings("restriction")
			public Object run() {
				try {
					Method getCleanerMethod = buffer.getClass().getMethod("cleaner", new Class[0]);
					getCleanerMethod.setAccessible(true);
					sun.misc.Cleaner cleaner = (sun.misc.Cleaner) getCleanerMethod.invoke(buffer, new Object[0]);
					cleaner.clean();
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}
		});
	}
	
	public static void umap(MappedByteBuffer buffer){
		
		try {
			Method cleaner = buffer.getClass().getMethod("cleaner");
			cleaner.setAccessible(true);
			Method clean = Class.forName("sun.misc.Cleaner").getMethod("clean");
			clean.setAccessible(true);
			clean.invoke(cleaner.invoke(buffer));
		} catch (Exception ex) {
		}
		buffer = null;
	}

}
